<script setup>
import {ref, onMounted, watch} from 'vue';
import axios from "@/axios/index.js";
import {defineProps} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";

const props = defineProps({
  courseId: {
    required: true
  },
  studentId: {
    type: String,
    required: true,
  },
})

const form = ref({
  feedback: ''
});

const formRef = ref(null);
const feedbackHistory = ref([]); // 存储历史反馈记录

/**
 * 获取学生ID
 */
/*const fetchStudentId = async () => {
  try {
    const response = await axios.get(`/api/v1/front/student/id`); // 假设你的接口是这样的
    studentId.value = response.data.id; // 根据实际返回的数据结构获取学生ID
  } catch (error) {
    console.error('获取学生ID失败:', error);
  }
};*/

/**
 * 获取历史反馈记录
 * @param courseId  课程id
 */
const fetchFeedbackHistory = (courseId) => {
  axios.get(`/api/v1/front/course/feedback/id/${courseId}/${props.studentId}`).then(res => {
    // console.log(res.data)
    feedbackHistory.value = res.data
    // console.log(feedbackHistory.value)
  })
};

const handleSubmit = () => {
  ElMessageBox.confirm('确认提交反馈吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value.validate((valid) => {
      if (valid) {
        const newFeedback = {
          feedbackOpinion: form.value.feedback,
          status: 'pending', // 初始状态为“pending”
          processingResult: '', // 初始处理结果为空
          studentId: props.studentId,
          courseId: props.courseId
        };
        axios.post('/api/v1/front/course', newFeedback).then(resp => {
          if (resp.data.code) {
            ElMessage({   //成功消息提示
              message: '反馈提交成功！',
              type: 'success',
              duration: 1000 // 可以设置持续时间，单位为毫秒
            });
            resetForm();  // 提交后重置表单
            fetchFeedbackHistory(newFeedback.courseId)  // 刷新历史反馈记录
          } else {
            alert(`提交失败:${resp.data.message}`)
          }
        }).catch(err => {
          console.error(err)
          alert('提交时发成错误，请重试。')
        });
      } else {
        console.log('验证失败!');
        return false;
      }
    });
  }).catch(()=>{})
};

// 在组件挂载时获取历史反馈记录
onMounted(() => {
  // console.log(props.courseId)
  fetchFeedbackHistory(props.courseId); // 使用从父组件传递过来的 courseId
});
// 监听 courseId 的变化
watch(() => props.courseId, async (newValue) => {
  await fetchFeedbackHistory(newValue);
});

/**
 * 提交后重置表单
 */
const resetForm = () => {
    form.value.feedback = '';
    formRef.value.clearValidate(); // 清除验证
};

//重置按钮
const reset = () => {
  ElMessageBox.confirm('确认重置表单吗？','提示',{
    confirmButtonText:'确认',
    cancelButtonText:'取消',
    type:'warning'
  }).then(()=>{
    form.value.feedback = '';
    formRef.value.clearValidate(); // 清除验证
  }).catch(()=>{})
}

</script>

<template>
  <el-container class="feedback-container">
    <el-header>

    </el-header>

    <el-form :model="form" ref="formRef" label-width="120px">
      <el-form-item label="反馈内容" prop="feedback"
                    :rules="[{ required: true, message: '请输入反馈内容', trigger: 'blur' }]">
        <el-input v-model="form.feedback" type="textarea" :rows=4></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交反馈</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-divider></el-divider>

    <h3>历史反馈记录</h3>
    <el-table :data="feedbackHistory" style="width: 100%">
      <el-table-column prop="feedbackOpinion" label="反馈内容"/>
      <el-table-column prop="status" label="处理状态"/>
      <el-table-column prop="processingResult" label="处理结果"/>
    </el-table>
  </el-container>
</template>

<style scoped>
</style>
